// packageF/pages/truck_entry_manage/add_driver/add_driver.js
const mybehavior = require("../../../../../behaviors/requests")
import WxValidate from "../../../../../Wx_Validate/WxValidate"
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [mybehavior],
  data: {
    submit_disabled: true,
    list: [],
    list1: [],
    list2: [],
    list3: [],
    list4: [],
    select_show: true,
    row_data: {},
    carry_data_list: {},
    flag: false,

  },
  setUpload2Value(e) {
    console.log(e);
    let array = e.detail
    let arr = []
    for (let i = 0; i < array.length; i++) {
      arr.push(array[i].file_id)
    }
    this.setData({
      imgID_list: arr
    })
    this.checkNullValue()


  },

  handle_delete(e) {
    const index = e.detail.index;
    const file = this.data.uploader[index];
    const file_id = file.url.split("=")[1];
    const uploader = this.data.uploader;
    const self = this;

    let url1 = self.data.img_url + '/fs_delete'
    let data = {
      file_id
    }
    this.post(url1, data, true).then(res => {
      if (res.code == 20000) {
        wx.showToast({
          title: res.msg,
          icon: 'success'
        })

        uploader.splice(index, 1);

        self.setData({
          uploader,
          power_of_attorney: ''
        });
        self.checkNullValue()
      } else {
        self.checkNullValue()
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      self.checkNullValue()
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },

  // 照片选取
  try_upload(e) {
    const self = this;
    // 关闭照片选取
    // 确定还有张图片可以选择
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const myUploadFiles = res.tempFiles.map(tempFile => {
          console.log("asfk;asflkjnsdlf", res);
          const tempFilePath = tempFile.tempFilePath;
          return self.myUploadFile(tempFilePath);
        });
        wx.showLoading({
          title: '开始上传。。。',
        })

        Promise.all(myUploadFiles).then(file_ids => {
          wx.hideLoading();
          // 处理UI
          console.log(file_ids);
          const uploader = self.data.uploader;

          const new_uploader = uploader.concat(file_ids.map(file_id => {
            return {
              url: self.data.img_url + '/fs_download?file_id=' + file_id,
              isImage: true,
              file_id: file_id

            };
          }));
          self.setData({
            uploader: new_uploader,
            power_of_attorney: file_ids[0]

          })
          console.log("xxx", self.data.uploader);
          wx.showToast({
            title: '上传成功！',
          });
          self.checkNullValue()

        }).catch(msg => {
          wx.hideLoading();

          self.checkNullValue()
          wx.showToast({
            title: msg,
            icon: "error"
          })
          console.log(msg);
        });
      },
      fail() {
      }
    })
  },

  myUploadFile(file) {

    console.log("xxx", file);
    let self = this
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: self.data.img_url + '/fs_upload',
        filePath: file,
        name: 'file',
        formData: {},
        success(res) {
          const result = JSON.parse(res.data);
          console.log(result);
          wx.hideLoading();
          if (result.code == 20000) {
            resolve(result.data.file_id);
          } else {
            reject(result.msg);
          }

        },
        fail() {
          reject("未知错误446");
        }
      })
    });
  },
  onRadioChange(e) {
    this.setData({
      is_weigh: e.detail
    })

    this.checkNullValue()
  },
  showToast() {
    let val = this.data.toast_show
    this.setData({
      toast_show: !val,

    })
  },

  // 单选下拉框下拉框
  getSelectRadioValue(e) {
    let key = e.currentTarget.dataset.id
    this.setData({
      [key]: e.detail.value
    })
    this.checkNullValue()
  },

  selectShow(e) {
    // console.log(e.detail.value);
    this.setData({
      select_show: e.detail.value
    })
  },
  // 提交携带物资
  submitCarry() {
    wx.showLoading({
      title: '处理中...',
    })
    let data = {
      supplier_number: this.data.supplier_number,
      tel: this.data.tel,
      license_plate_number: this.data.license_plate_number,
      area: this.data.area,
      material_information: this.data.material_information,
      imgID_list: this.data.imgID_list,
      is_enter: "是",
    }
    console.log('提交携带物资', data);
    let url = "/material_registration_manage/material_registration_add_material";


    this.post(url, data).then(res => {
      // console.log("返回回收类别结果", res)
      if (res.code == 20000) {

        wx.hideLoading()
        wx.showToast({
          title: res.msg,
          icon: "success"
        });
      } else {
        wx.hideLoading()
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  // 提交临时预约
  sumbitShortTime() {
    wx.showLoading({
      title: '处理中...',
    })
    let data = {
      _id: this.data._id,
      supplier_number: this.data.supplier_number,
      area: this.data.area,
      unit: this.data.unit,
      name: this.data.name,
      tel: this.data.tel,
      identification_card_number: this.data.identification_card_number,
      license_plate_number: this.data.license_plate_number,
      specification: this.data.specification,
      car_type: this.data.car_type,
      power_of_attorney: this.data.power_of_attorney,
      reason: this.data.reason,
      business_type: this.data.business_type,//业务类型
      current_involved: this.data.current_involved,
      is_weigh: this.data.is_weigh,
      warehouse: this.data.warehouse,
      gates: this.data.gates,
      material_code: this.data.material_code,
      filing_date: this.data.filing_date,
      expiry_date: this.data.expiry_date,
    }
    console.log('提交临时预约', data);

    let url = "/entrance_manage/submit_temp_reservation";


    this.post(url, data).then(res => {
      // console.log("返回回收类别结果", res)
      if (res.code == 20000) {

        wx.hideLoading()
        wx.showToast({
          title: res.msg,
          icon: "success"
        });
        this.submitCarry()
      } else {
        wx.hideLoading()
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })

  },

  onCheckboxChange(e) {

    console.log(e);
    this.setData({
      checkbox_list: e.detail
    })

  },
  // 检测输入值是否为空
  checkNullValue() {
    let that = this
    let data = {
      supplier_number: this.data.supplier_number,
      area: this.data.area,
      unit: this.data.unit,
      name: this.data.name,
      tel: this.data.tel,
      identification_card_number: this.data.identification_card_number,
      license_plate_number: this.data.license_plate_number,
      specification: this.data.specification,
      car_type: this.data.car_type,
      power_of_attorney: this.data.power_of_attorney,
      reason: this.data.reason,
      // business_type: this.data.business_type,//业务类型
      current_involved: this.data.current_involved,
      is_weigh: this.data.is_weigh,
      warehouse: this.data.warehouse,
      gates: this.data.gates,
      material_code: this.data.material_code,
      filing_date: this.data.filing_date,
      expiry_date: this.data.expiry_date,

      material_information: this.data.material_information,
      imgID_list: this.data.imgID_list,

    }
    if (!that.WxValidate.checkForm(data)) {
      const error = that.WxValidate.errorList[0]
      console.log(error);
      that.setData({
        submit_disabled: true,
      })
    } else {
      that.setData({
        submit_disabled: false,
      })
    }
  },
  //初始化表单验证规则
  initValidate() {
    let rules = {
      supplier_number: {
        required: true,
      },
      unit: {
        required: true,
      },
      area: {
        required: true,
      },
      name: {
        required: true,
      },

      tel: {
        required: true,
      },
      identification_card_number: {
        required: true,
      },
      license_plate_number: {
        required: true,
      },
      specification: {
        required: true,
      },
      car_type: {
        required: true,
      },
      power_of_attorney: {
        required: true,
      },
      reason: {
        required: true,
      },
      // business_type: {
      //   required: true,
      // },
      current_involved: {
        required: true,
      },
      is_weigh: {
        required: true,
      },
      warehouse: {
        required: true,
      },
      gates: {
        required: true,
      },
      // material_code: {
      //   required: true,
      // },
      filing_date: {
        required: true,
      },
      expiry_date: {
        required: true,
      },

      material_information: {
        required: true,
      },
      imgID_list: {
        required: true,
      },


    }

    let message = {
      supplier_number: {
        required: "供应商号码-不能为空",
      },
      area: {
        required: "送货园区-不能为空",
      },

      unit: {
        required: "单位-不能为空",
      },

      name: {
        required: "姓名-不能为空",
      },
      tel: {
        required: "电话号码-不能为空",
      },
      identification_card_number: {
        required: "身份证号码-不能为空",
      },
      license_plate_number: {
        required: "车牌号-不能为空",
      },
      specification: {
        required: "车辆规格-不能为空",
      },
      car_type: {
        required: "车辆类型-不能为空",
      },
      power_of_attorney: {
        required: "委托授权书-不能为空",
      },
      reason: {
        required: "备案原因-不能为空",
      },
      // business_type: {
      //   required: "业务类型-不能为空",
      // },
      current_involved: {
        required: "当前审批人-不能为空",
      },
      is_weigh: {
        required: "是否过磅-不能为空",
      },
      warehouse: {
        required: "送货仓库-不能为空",
      },
      gates: {
        required: "出入门岗-不能为空",
      },

      // material_code: {
      //   required: "送货单号-不能为空",
      // },
      filing_date: {
        required: "开始日期-不能为空",
      },
      expiry_date: {
        required: "结束日期-不能为空",
      },

      material_information: {
        required: "携带物资信息-不能为空",
      },
      imgID_list: {
        required: "携带物资图片-不能为空",
      },




    }
    //实例化当前的验证规则和提示消息
    this.WxValidate = new WxValidate(rules, message);
  },
  // 获取携带信息数据
  getCarryInfo() {
    let url = "/material_registration_manage/material_registration_query_material";
    let data = {
      supplier_number: this.data.row_data.supplier_number,
      tel: this.data.row_data.tel,
      license_plate_number: this.data.row_data.license_plate_number,
      area: this.data.row_data.area,
    }
    console.log(data);
    this.post(url, data).then(res => {
      if (res.code == 20000) {
        console.log("获取携带信息数据", res);
        let array = res.data.results
        this.setData({
          carry_data_list: array
        })
      } else {
        console.log(err);
        // wx.showToast({
        //     title: res.msg,
        //     icon: "error"
        //   })
      }
    }).catch(err => {
      console.log("xxx", err);
      // wx.showToast({
      //   title: err.msg,
      //   icon: 'error'
      // })
    })
  },
  // 获取后台配置项
  getBackstage() {
    let url = "/entrance_manage/get_backstage";
    let data = {
      // unit: '供应商',
      // car_type: ['箱式货车', '飞翼车', '其他'],
      // specification: ['4米2', '6米8', '9米6', '13米', '其他',],
      // gates: ['5号门', '9号门', '13号门'],
      // business_type: ['物资车辆--送货', '物资车辆--装货', '物资车辆--送、装货', '成品车辆--装货', '其他车辆--内部外聘',],
      // templates: ['携带物资信息', '其他信息',],
      // warehouse: ['南门货场', '物流中心', '物资大楼', '双子座A', '双子座B','505仓库'],

      page: 1,
      pagesize: 999,
    }

    this.post(url, data).then(res => {
      console.log("返回后台配置结果", res)
      if (res.code == 20000) {
        this.setData({
          list1: res.data.results[0].gates,
          list2: res.data.results[0].business_type,
          list3: res.data.results[0].specification,
          list4: res.data.results[0].car_type,

        })

      } else {
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate()
    let self = this
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', function (data, flag) {
      console.log(data);
      self.setData({
        row_data: data,
        flag: flag
      })
      self.getCarryInfo()
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getBackstage()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})